package de.herzog.bbp.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public abstract class FileArchiver {

	private static final Comparator<? super File> FILE_DATE_COMPARATOR = (file1, file2) -> new Date(
			file1.lastModified()).compareTo(new Date(file2.lastModified()));

	public static void createArchiveFile(String fileName) throws IOException {
		int pos = fileName.lastIndexOf('.');
		String extension = fileName.substring(pos);
		String fileNameWoExtension = fileName.substring(0, pos) + "-";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
		String archiveFileName = fileNameWoExtension + sdf.format(new Date()) + extension;
		Files.copy(Paths.get(fileName), Paths.get(archiveFileName));
		deleteOldArchiveFiles(fileName, fileNameWoExtension, 5);
	}

	private static void deleteOldArchiveFiles(String fileName, String fileNameWoExtension, int keepCount) {
		File folder = new File(fileName).getParentFile();
		List<File> files = Arrays.asList(folder.listFiles()).stream() //
				.filter(file -> file.isFile()) //
				.filter(file -> file.getAbsolutePath().startsWith(fileNameWoExtension)) //
				.sorted(FILE_DATE_COMPARATOR) //
				.collect(Collectors.toList());
		int deleteCount = Math.max(files.size() - keepCount, 0);
		files.subList(0, deleteCount).forEach(file -> file.delete());
	}

	static void deleteFolderRecursively(String folderName) throws IOException {
		if (Files.exists(Paths.get(folderName))) {
			Files.walkFileTree(Paths.get(folderName), new SimpleFileVisitor<Path>() {
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					Files.delete(file);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
					Files.delete(dir);
					return FileVisitResult.CONTINUE;
				}
			});
		}
	}
}
